<?php

namespace Phones\MainBundle\Entity;

class ModelRepository extends Repository {

    public function findByBrand(Brand $brand, $page = 1) {
        return $this->find(array(
            'conditions' => array('Model.brand' => $brand->id)
        ));
    }

    public function search($keyword, $limit = false) {
        $qb = $this->buildQuery($keyword)
                   ->select(array('m', 'b'));
        if ($limit) {
            $qb->setMaxResults($limit);
        }

        return $qb->getQuery()->getResult();
    }

    public function searchTotal($keyword) {
        return $this->buildQuery($keyword)
                    ->select('COUNT(m)')
                    ->getQuery()
                    ->getSingleScalarResult();
    }

    public function all($page = 1, $limit = 10) {
        $qb = $this->buildQuery()
                   ->setFirstResult($limit * ($page-1))
                   ->setMaxResults($limit);
        $result = $qb->getQuery()->getResult();

        $total  = $this->buildQuery()
                       ->select('COUNT(m)')
                       ->getQuery()
                       ->getSingleScalarResult();
        
        return array($result, $total);
    }

    private function buildQuery($keyword = null) {
        $qb = $this->createQueryBuilder('m')
                   ->innerJoin("m.brand", 'b')
                   ->orderBy('b.name, m.name');
        if ($keyword) {
            $fields = array(
                'm.name',
                'm.software',
                'b.name',
                'CONCAT(b.name, CONCAT(\' \', m.name))'
            );
            $conditions = implode(' LIKE :keyword OR ', $fields) . ' LIKE :keyword';
            $qb->where($conditions)
               ->setParameter('keyword', '%'.$keyword.'%');
        }
        return $qb;
    }
}